<?php
namespace Api\Controller;
use Think\Controller;
class GoodsController extends CommonController {
    public function index(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = ((int)$page + 1) * 10;
        } else {
            $page = 0;
        }

        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        if($_GET['openid']){
            $map['openid'] = $_GET['openid'];
        }
        if($_GET['shop_id']){
            $map['shop_id'] = $_GET['shop_id'];
        }
        if($_GET['type']){
            $map['type'] = $_GET['type'];
        }else{
            $map['type'] = '';
        }
        if($_GET['huodong']){
            switch ($_GET['huodong']) {
                case 'pin':
                    $map['is_pin'] = 1;
                    $map['status']=1;

                    //
                    $list = array('', '', '');
                    foreach ($map as $key => $value) {
                        $map['a.'. $key] = $value;
                        unset($map[$key]);
                    }
                    $map['b.is_shield'] = 0;//屏蔽
                    $listKan = M("Goods")->alias('a')
                        ->field('a.*, b.join_end_time, b.cate')
                        ->join('tp_shop b on a.shop_id = b.shop_id')
                        ->where($map)
                        ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                        ->order("last_time desc")
                        ->limit(0, $page)
                        ->select();
                    if ($_GET['clickType']) { //抢购检索
                        $wid= session('wid');
                        $typeArr = array('全部', '美食', '娱乐', '购物', '丽人');
                        $cate = $typeArr[$_GET['clickType']];
                        $eat = M('cate')->where(['title' => $cate, 'pid' => '0', 'wid' => $wid])->find();
                        $eatSonArr = M('cate')->where(['pid' => $eat['id']])->select();
                        $eatAllArr = array($cate);
                        foreach ($eatSonArr as $key => $value) {
                            $eatAllArr[] = $value['title'];
                        }
                        foreach ($listKan as $key => $value) {
                            if (!in_array($value['cate'], $eatAllArr)) {
                                unset($listKan[$key]);
                            }
                        }
                    }
                    foreach ($listKan as $key => $value) {
                        $list[1][] = $listKan[$key];// ?
//                        $count =  M('kan_log')->where(['goods_id' => $value['id'], 'openid' => ['NEQ', $value['openid']]])->count();
//                        if ($value['kan_need_num'] == $count) { //抢购结束
//                            $list[2][] = $listKan[$key];
//                        } else {
//                            $kanArr = M('kan_log')->where(['goods_id' => $value['id'], 'openid' => $value['openid']])->select();
//                            foreach ($kanArr as $k => $v) {
//                                $v['kan_openid'] ? $isHaveKanMan = 1 : '';
//                            }
//                            if (isset($isHaveKanMan)) { //抢购进行中
//                                $list[1][] = $listKan[$key];
//                            } else { //待抢购
//                                $list[0][] = $listKan[$key];
//                            }
//                        }
                    }
                    $this->ajaxReturn($list);
                    //
                    break;
                case 'kan'://砍价数据获取
                    $map['is_kan'] = 1;

                    //
                    $list = array('', '', '');
                    foreach ($map as $key => $value) {
                        $map['a.'. $key] = $value;
                        unset($map[$key]);
                    }
                    $map['b.is_shield'] = 0;//屏蔽
                    $listKan = M("Goods")->alias('a')
                                        ->field('a.*, b.join_end_time, b.cate')
                                        ->join('tp_shop b on a.shop_id = b.shop_id')
                                        ->where($map)
                                        ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                                        ->order("last_time desc")
                                        ->limit(0, $page)
                                        ->select();
                    if ($_GET['clickType']) { //砍价检索
                        $wid= session('wid');
                        $typeArr = array('全部', '美食', '娱乐', '购物', '丽人');
                        $cate = $typeArr[$_GET['clickType']];
                        $eat = M('cate')->where(['title' => $cate, 'pid' => '0', 'wid' => $wid])->find();
                        $eatSonArr = M('cate')->where(['pid' => $eat['id']])->select();
                        $eatAllArr = array($cate);
                        foreach ($eatSonArr as $key => $value) {
                            $eatAllArr[] = $value['title'];
                        }
                        foreach ($listKan as $key => $value) {
                            if (!in_array($value['cate'], $eatAllArr)) {
                                unset($listKan[$key]);
                            }
                        }
                    }
                   foreach ($listKan as $key => $value) {
                       $count =  M('kan_log')->where(['goods_id' => $value['id'], 'openid' => ['NEQ', $value['openid']]])->count();
                       if ($value['kan_need_num'] == $count) { //砍价结束
                           $list[2][] = $listKan[$key];
                       } else {
                           $kanArr = M('kan_log')->where(['goods_id' => $value['id'], 'openid' => $value['openid']])->select();
                           foreach ($kanArr as $k => $v) {
                               $v['kan_openid'] ? $isHaveKanMan = 1 : '';
                           }
                           if (isset($isHaveKanMan)) { //砍价进行中
                               $list[1][] = $listKan[$key];
                           } else { //待砍价
                               $list[0][] = $listKan[$key];
                           }
                       }
                   }
                    $this->ajaxReturn($list);
                    //
                    break;
                case 'qiang': //抢购数据获取
                    $map['is_qiang'] = 1;

                    //
                    $list = array('', '', '');
                    foreach ($map as $key => $value) {
                        $map['a.'. $key] = $value;
                        unset($map[$key]);
                    }
                    $map['b.is_shield'] = 0;//屏蔽
                    $listKan = M("Goods")->alias('a')
                                        ->field('a.*, b.join_end_time, b.cate')
                                        ->join('tp_shop b on a.shop_id = b.shop_id')
                                        ->where($map)
                                        ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                                        ->order("last_time desc")
                                        ->limit(0, $page)
                                        ->select();
                    if ($_GET['clickType']) { //抢购检索
                        $wid= session('wid');
                        $typeArr = array('全部', '美食', '娱乐', '购物', '丽人');
                        $cate = $typeArr[$_GET['clickType']];
                        $eat = M('cate')->where(['title' => $cate, 'pid' => '0', 'wid' => $wid])->find();
                        $eatSonArr = M('cate')->where(['pid' => $eat['id']])->select();
                        $eatAllArr = array($cate);
                        foreach ($eatSonArr as $key => $value) {
                            $eatAllArr[] = $value['title'];
                        }
                        foreach ($listKan as $key => $value) {
                            if (!in_array($value['cate'], $eatAllArr)) {
                                unset($listKan[$key]);
                            }
                        }
                    }
                    foreach ($listKan as $key => $value) {
                        $list[1][] = $listKan[$key];// ?
//                        $count =  M('kan_log')->where(['goods_id' => $value['id'], 'openid' => ['NEQ', $value['openid']]])->count();
//                        if ($value['kan_need_num'] == $count) { //抢购结束
//                            $list[2][] = $listKan[$key];
//                        } else {
//                            $kanArr = M('kan_log')->where(['goods_id' => $value['id'], 'openid' => $value['openid']])->select();
//                            foreach ($kanArr as $k => $v) {
//                                $v['kan_openid'] ? $isHaveKanMan = 1 : '';
//                            }
//                            if (isset($isHaveKanMan)) { //抢购进行中
//                                $list[1][] = $listKan[$key];
//                            } else { //待抢购
//                                $list[0][] = $listKan[$key];
//                            }
//                        }
                    }
                    $this->ajaxReturn($list);
                    //
                    break;
            }
        }
//        $list = M("Goods")->where($map)->order("last_time desc")->select();
        foreach ($map as $key => $value) {
            $map['a.'. $key] = $value;
            unset($map[$key]);
        }
        $list = M("Goods")->alias('a')
                          ->field('a.*, b.join_end_time')
                          ->join('tp_shop b on a.shop_id = b.shop_id')
                          ->where($map)
                          ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                          ->order("last_time desc")
                          ->limit(0, $page)
                          ->select();
        $this->ajaxReturn($list);
    }

    public function item(){
        //$map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $info = M("Goods")->where($map)->find();
        $info['pics'] = explode(",", $info['pics']);
        if($info['is_qiang'] == 1){
            if(date("Y-m-d H:i") < $info['start_date'].' '.$info['start_time']){
                $info['qiang_time'] = 0;
            }elseif(date("Y-m-d H:i") > $info['end_date'].' '.$info['end_time']){
                $info['qiang_time'] = 2;
            }else{
                $info['qiang_time'] = 1;
            }
        }
        $yh = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();
        if($yh){
            $info['is_yh'] = 1;
            $info['yh_discount'] =$yh['discount'];
        }
        if($info['type'] == 'car'){
            $info['car_info'] = S("cardetail{$info['car_id']}");
        }

        if($info['is_pin'] == 1){
            $eq['is_pay'] = 1;
            $eq['status'] = 0;
            $eq['is_tuan'] = 1;
            $eq['goods_id'] = $info['id'];
            $eq['is_tuan_first'] = 1;
            $eq['tuan_need_num'] = array('exp',' > tuan_pay_num ');
            
            $info['tuan_order_count'] = M("Order")->where($eq)->count();
            $info['tuan_order_list'] = M("Order")->where($eq)->limit(3)->order('id desc')->select();

            

            foreach ($info['tuan_order_list'] as $k => $v) {
                $eq2['openid'] = $v['openid'];
                $user = M("Member")->where($eq2)->find();

                    $eq4['is_pay'] = 1;
                    $eq4['status'] = 0;
                    $eq4['is_tuan'] = 1;
                    $eq4['goods_id'] = $info['id'];
                    $eq4['tuan_first_id'] =  $info['tuan_order_list'][$k]['id'];
                    $tuan_count= M("Order")->where($eq4)->count();
                    $info['tuan_order_list'][$k]['left_count']= $info['tuan_order_list'][$k]['tuan_need_num']-$tuan_count-1;

                $info['tuan_order_list'][$k]['nickname'] = $user['nickname'];
                $info['tuan_order_list'][$k]['headimgurl'] = $user['headimgurl'];
            }
            $info['tuan_first_id']= $info['tuan_order_list'][0]['id'];
        }
        if(I("type" == 'kan') && $info['is_kan']){
            $eq1['goods_id'] = I('id');
            $eq1['openid'] = I("openid");
            $eq1['kan_openid'] = I("kan_openid");
            if(M("KanLog")->where($eq1)->find()){
                $info['has_kan'] = true;
            }

            /*我添加的*/
            $eq3['goods_id'] = I('id');
            $eq3['kan_price']=array('exp',' > 0 ');
            $eq3['openid'] = I("openid");

            $info['kan_order_list'] = M("KanLog")->where($eq3)->limit(5)->select();
          //  $info['kan_order_list'] =array_shift($info['kan_order_list']);
            foreach ($info['kan_order_list'] as $k => $v) {
                $eq2['openid'] = $v['kan_openid'];
                $user = M("Member")->where($eq2)->find();
                $info['kan_order_list'][$k]['nickname'] = $user['nickname'];
                $info['kan_order_list'][$k]['headimgurl'] = $user['headimgurl'];
            }

        }
        if($info['is_kan']){
            $eq3['goods_id'] = I('id');
            $eq3['openid'] = I("openid");
            $eq3['kan_price']=array('exp',' > 0 ');

            $kan_total = M("KanLog")->where($eq3)->sum("kan_price");
            $kan_total1 = M("KanLog")->where($eq3)->count();



            $eq5['goods_id'] = I('id');
            $kan_total2 = M("KanLog")->where($eq5)->count();



            if(!$kan_total){
                $kan_total = 0;
            }else{
                $kan_total=$kan_total;
            }
            $info['kan_left'] = intval($info['kan_need_num'])-$kan_total1;
            $info['kan_progress'] = $kan_total/($info['price'] - $info['kan_price'])*100;
            $info['kan_total'] = sprintf("%.2f",$kan_total);
            $info['kan_total1'] = $kan_total1;
            $info['kan_total2'] = $kan_total2;

        }

        $this->ajaxReturn($info);
    }

    // 拼团
    public function tuanShare(){
        $map['wid'] = session('wid');
        // $map['openid'] = I("openid");
        $map['is_pay'] = 1;
        $map['is_tuan'] = 1;

        if(!I("id")){
            $order = M("Order")->where($map)->order('id desc')->find();
        }else{
            $map['id'] = I("id");
            $order = M("Order")->where($map)->find();
        }
        $map1['is_pay'] = 1;
        $map1['is_tuan'] = 1;

        if(!$order){
              $order = M("Order")->where($map1)->order('id desc')->find();

        }


        if(!$order){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        $eq['id'] = $order['goods_id'];
        $res['goods_info'] = M("Goods")->where($eq)->find();

        $eq1['tuan_first_id'] = $order['id'];
        $eq1['is_pay'] = 1;
        $order_list = M("Order")->where($eq1)->select();
        array_unshift($order_list, $order);


        $tuan_order_count = M("Order")->where($eq1)->count();

        $res['is_join'] = false;
        foreach ($order_list as $k => $v) {
            if($v['openid'] == I('openid')){
                $res['is_join'] = true;
            }
            $eq2['openid'] = $v['openid'];
            $user = M("Member")->where($eq2)->find();
            $order_list[$k]['nickname'] = $user['nickname'];
            $order_list[$k]['headimgurl'] = $user['headimgurl'];
            $order_list[$k]['tuan_pay_num'] = $tuan_order_count+1;
        }
        $res['order_list'] = $order_list;
        $this->ajaxReturn($res);
    }

    // 砍价
    public function addKanLog(){
        $eq['goods_id'] = I('id');
        $eq['openid'] = I("openid");
        if(!M("KanLog")->where($eq)->find()){
            M("KanLog")->add($eq);
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }
        if(I("type")){
            $eq['kan_openid'] = I("kan_openid");
            if(M("KanLog")->where($eq)->find()){
                $arr = array("err_code"=>400,"err_msg"=>"你已经帮Ta砍过了~");
                $this->ajaxReturn($arr);
            }else{
                $eq['kan_price'] = $this->getKanPrice();
                M("KanLog")->add($eq);
                $kanid = M()->getLastInsID();
                $arr = array("err_code"=>0, "err_msg"=>"成功帮Ta砍掉{$eq['kan_price']}元！");

                //发送通知
                $eq3['goods_id'] = I('id');
                $eq3['openid'] = I("openid");
                $eq3['kan_price']=array('exp',' > 0 ');
                $kan_total1 = M("KanLog")->where($eq3)->count();
                $map['wid'] = session('wid');
                $map['id'] = I('id');
                $info = M("Goods")->where($map)->find();
                //一共砍价多少钱
                $kan_total = M("KanLog")->where($eq3)->sum("kan_price");
                if(!$kan_total){
                    $kan_total = 0;
                }else{
                    $kan_total=$kan_total;
                }
                $kan_total= sprintf("%.2f",$kan_total);
                $kan_num = intval($info['kan_need_num'])-$kan_total1;
                if((intval($info['kan_need_num'])-$kan_total1) <= 0){
                    //砍价成功通知
                    sendKanMessage(I("openid"),$kanid,$kan_num>0?$kan_num:1,$kan_total,session('wid'),"end");
                }else{
                    //砍价进度通知
                    sendKanMessage(I("openid"),$kanid,$kan_num>0?$kan_num:1,$kan_total,session('wid'),"ing");
                }

                $this->ajaxReturn($arr);
            }
        }
    }

    public function getKanPrice(){
        $map['id'] = I("id");
        $map['wid'] = session('wid');
        $good = M("Goods")->where($map)->find();

        $eq['goods_id'] = I('id');
        $eq['openid'] = I("openid");

        $kan_total = M("KanLog")->where($eq)->sum("kan_price");
        $kan_count = M("KanLog")->where($eq)->count();
        if(!$kan_total){
            $kan_total = 0;
        }
        $money_total = $good['price'] - $good['kan_price'] - $kan_total;
        if($money_total <= 0){
            $arr = array("err_code"=>400,"err_msg"=>"已经砍到最低价了~");
            $this->ajaxReturn($arr);
        }
        $num = $good['kan_need_num'] - $kan_count+1;

        if($money_total < $num*0.01) {  
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);  
        }  
      
        $rand_arr = array();  
        for($i=0; $i<$num; $i++) {  
            $rand = rand(1, 100);  
            $rand_arr[] = $rand;  
        }  
      
        $rand_sum = array_sum($rand_arr);  
        $rand_money_arr = array();  
        $rand_money_arr = array_pad($rand_money_arr, $num, 0.01);  //保证每个红包至少0.01  
      
        foreach ($rand_arr as $key => $r) {  
            $rand_money = number_format($money_total*$r/$rand_sum, 2);  
      
            if($rand_money <= 0.01 || number_format(array_sum($rand_money_arr), 2) >= number_format($money_total, 2)) {  
                $rand_money_arr[$key] = 0.01;  
            } else {  
                $rand_money_arr[$key] = $rand_money;  
            }  
      
        }  
      
        $max_index = $max_rand = 0;  
        foreach ($rand_money_arr as $key => $rm) {  
            if($rm > $max_rand) {  
                $max_rand = $rm;  
                $max_index = $key;  
            }  
        }  
      
        unset($rand_money_arr[$max_index]);  
        //这里的array_sum($rand_money_arr)一定是小于$money_total的  
        $rand_money_arr[$max_index] = number_format($money_total - array_sum($rand_money_arr), 2);  
          
        ksort($rand_money_arr);
        return $rand_money_arr[0];
    }
    // 生成商品购买订单
    public function addGoodsOrder(){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $map2['id'] = $_POST['id'];
        $info = M("Goods")->where($map2)->find();
        if(!$info){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
        // 抢购时间验证
        if($info['is_qiang'] == 1){
            if(date("Y-m-d H:i") < $info['start_date'].' '.$info['start_time']){
                $arr = array("err_code"=>400,"err_msg"=>"抢购尚未开始~");
                $this->ajaxReturn($arr);
            }elseif(date("Y-m-d H:i") > $info['end_date'].' '.$info['end_time']){
                $arr = array("err_code"=>400,"err_msg"=>"抢购已经结束了，下次早点来哦~");
                $this->ajaxReturn($arr);
            }
        }
        // 验证库存
        if($info['stock'] <= 0){
            $arr = array("err_code"=>400,"err_msg"=>"你要买的东西已经被抢光了~");
            $this->ajaxReturn($arr);
        }
        // 限购验证
        if($info['is_xian']){
            $eq['is_pay'] = 1;
            $eq['goods_id'] = $info['id'];
            $eq['openid'] = $_POST['openid'];
            $order_num = M("Order")->where($eq)->count();
            if($order_num >= $info['max_num'] && $info['max_num']!=0){
                $arr = array("err_code"=>400,"err_msg"=>"该商品每人限购{$info['max_num']}件~");
                $this->ajaxReturn($arr);
            }
        }
        
        if($_POST['type'] === 'pin'){
            $data['is_tuan'] = 1;
            $data['is_tuan_first'] = 1;
        }
        //参加拼团
        if($_POST['type'] === 'join'){
            $data['is_tuan'] = 1;
            $data['tuan_first_id'] = $_POST['tuan_first_id'];

            // 验证拼团状态
            $eq1['id'] = $_POST['tuan_first_id'];
            $eq1['is_pay'] = 1;
            $tuan_order = M("Order")->where($eq1)->find();
            if(!$tuan_order){
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
            $eq1['openid'] = I('openid');
            if( $tuan_order['openid'] == I('openid') || M("Order")->where($eq1)->find() ){
                $arr = array("err_code"=>400,"err_msg"=>"你已经参与过该团了！");
                $this->ajaxReturn($arr);
            }
            if($tuan_order['tuan_need_num'] <= $tuan_order['tuan_pay_num']){
                $arr = array("err_code"=>400,"err_msg"=>"该团已经拼团成功，请参与其他拼团~");
                $this->ajaxReturn($arr);
            }
        }
        if($data['is_tuan'] == 1){
            $info['price'] = $info['tuan_price'];
            $data['tuan_need_num'] = $info['tuan_need_num'];
        }
        //砍价
        if($_POST['type'] === 'kan'){
            $eq3['goods_id'] = I('id');
            $eq3['openid'] = I("openid");

            $kan_total = M("KanLog")->where($eq3)->sum("kan_price");
            if(!$kan_total){
                $kan_total = 0;
            }
            if($info['kan_need_min'] == 1 && $kan_total != $info['price'] - $info['kan_price']){
                $arr = array("err_code"=>400,"err_msg"=>"需要砍到最低价才能购买哦~");
                $this->ajaxReturn($arr);
            }
            // dump($kan_total);
            $info['price'] = round($info['price'] - $kan_total,2);//随机砍价
            $data['coupon_price'] = $kan_total;
            $data['is_kan'] = 1;
        }
        $price = $info['price'];//原价
        //店铺是否参与同城卡
        $rowShopTCard = M('shop_card_yh')->where(['shop_id' => $info['shop_id'], 'wid' => session('wid'), 'status' => 1])->find();
        if ($rowShopTCard) {
            //使用次数和使用人数
            $yh_member = M('shop_order')->where(['is_pay'=>1,'is_card_yh'=>1,'shop_id'=>$info['shop_id']])->count();//使用人数
            $yh_count = M('shop_order')->where(['is_pay'=>1,'is_card_yh'=>1,'openid'=>$_POST['openid']])->count();//使用次数
            if ($yh_member< $rowShopTCard['count'] && $yh_count< $rowShopTCard['frequency']) {
                //用户是否开通同城卡
                $wherep['is_pay'] = 1;
                $wherep['end_time'] = ['GT', date('Y-m-d H:i:s', time())];
                $wherep['wid'] = session('wid');
                $wherep['openid'] = $_POST['openid'];
                $card = M('card_log')->where($wherep)->find();
                if ($card) {
                    //无属性商品会员价格 && 抢购会员价格
                    if ($_POST['type'] === null) {
                        $price = $info['vip_price'];
                    }
                    //拼团会员价格
                    if ($_POST['type'] === 'pin') {
                        $price = $info['vip_pin_price'];
                    }
                    //砍价成功会员价格
                    if ($_POST['type'] === 'kan') {
                        $price = $info['vip_kan_price'];
                    }
                }
            }
        }
//        //判断用户是否开通同城卡
//        $wherep['is_pay'] = 1;
//        $wherep['end_time'] = ['GT', date('Y-m-d H:i:s', time())];
//        $wherep['wid'] = session('wid');
//        $card = M('card_log')->where($wherep)->find();
//        if($card){
//            //商家是否有同城卡优惠
//            $yh = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();
//            if($yh){
//                //商家有同城卡
//                //使用次数和使用人数
//                $yh_member = M('shop_order')->where(['is_pay'=>1,'is_card_yh'=>1,'shop_id'=>$info['shop_id']])->count();//使用人数
//                $yh_count = M('shop_order')->where(['is_pay'=>1,'is_card_yh'=>1,'openid'=>$_POST['openid']])->count();//使用次数
//                if($yh_member< $yh['count'] && $yh_count< $yh['frequency']){
//                    //符合要求
//                    $price = $price * $yh['discount']/10;
//                }
//            }
//        }
        //分销
        if($info['is_commission']){
            $data['commission_one'] =$info['commission_one'];//一级佣金比例
            $data['commission_two'] =$info['commission_two'];//二级佣金比例
            $data['is_commission'] = 1;
        }

        $data['wid'] = $info['wid'];
        $data['shop_id'] = $info['shop_id'];
        $data['goods_id'] = $info['id'];
        $data['openid'] = $_POST['openid'];
        $data['out_trade_no'] = $this->build_order_no();
        $data['title'] = $info['title'];
        $data['img_url'] = $info['img_url'];
        $data['remark'] = $info['remark'];
        $data['content'] = $info['content'];
        $data['price'] = $price;
        $data['num'] = 1;
        $data['pay_money'] = $price;
        $data['status'] = 1;
        $data['is_pay'] = 0;
        $data['create_time'] = date("Y-m-d H:i:s");
        if(!M("Order")->add($data)){
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/index",array('type'=>'goods'));
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        if(!$data['remark']){
            $data['remark'] = "智联同城";
        }
        $input->SetBody($data['remark']);
        $input->SetAttach($data['title']);
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($data['pay_money']*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage().$data['pay_money']);
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg'].$data['pay_money']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
       // 获取最新的orderid
        $map3['openid']=$data['openid'];
        $list = M("Order")->where($map3)->order("id desc")->select();
        $orderid=$list[0]['id'];
        // $jsApiParametersarr =json_decode($jsApiParameters);
        // $jsApiParametersarr['id']=$orderid;
        // $jsApiParameters = json_encode($jsApiParametersarr);
        echo $jsApiParameters;
    }

    public function getAddForm(){
        if($_GET['id']){
            switch ($_GET['type']) {
                case 'qiang':
                    $res = $this->getQiangForm();
                    break;
                case 'pin':
                    $res = $this->getPinForm();
                    break;
                case 'kan':
                    $res = $this->getKanForm();
                    break;
                default:
                    $res = $this->getEditForm();
                    break;
            }
        }else{
            $info = M('shop')->where(['openid'=>I('openid'),'status'=>1,'is_pay'=>1,'join_end_time'=>['gt', date('Y-m-d H:i:s', time())]])->order('create_time desc')->find();
            $shop = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();//是否开通和同城卡
            $pics = array();
            $res['add_url'] = "https://www.58zltc.com/api.php/Goods/add";
            $form[] = array('type'=>'text', 'title'=>'商品名称', 'name'=>'title');
            $form[] = array('type'=>'digit', 'title'=>'销售价', 'name'=>'price');
            $form[] = array('type'=>'digit', 'title'=>'原价', 'name'=>'old_price');
            if($shop){
                $form[] = array('type'=>'digit', 'title'=>'会员价', 'name'=>'vip_price', 'value'=>$info['vip_price']);
                //商品参与分销以及佣金
                $form[] = array('type'=>'checkbox', 'title'=>'参与分销', 'name'=>'is_commission', 'value'=>0, 'checked'=>false);
                $form[] = array('type'=>'number', 'title'=>'一级佣金比例(%)', 'name'=>'commission_one', 'value'=>$info['commission_one']);
                $form[] = array('type'=>'number', 'title'=>'二级佣金比例(%)', 'name'=>'commission_two', 'value'=>$info['commission_two']);
            }
            $form[] = array('type'=>'number', 'title'=>'库存', 'name'=>'stock');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'checkbox', 'title'=>'开启限购', 'name'=>'is_xian', 'value'=>0, 'checked'=>false);
            $form[] = array('type'=>'number', 'title'=>'每人限购件数', 'name'=>'max_num', 'value'=>$info['max_num']);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'商品图片', 'name'=>'pics', 'num'=>2, 'pics'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'商品简介', 'name'=>'content');
            $res['form'] = $form;
        }
        $res['index_url'] = "/pages/mine/shop/goods/list";
        $this->ajaxReturn($res);
    }
    // 获取商品编辑表单
    private function getEditForm(){
        $map['id'] = $_GET['id'];
        $info = M("Goods")->where($map)->find();
        $shop = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();//添加会员价
        $pics = explode(',', $info['pics']);
        $res['add_url'] = "https://www.58zltc.com/api.php/Goods/add/id/{$_GET['id']}";
        $form[] = array('type'=>'text', 'title'=>'商品名称', 'name'=>'title', 'value'=>$info['title']);
        $form[] = array('type'=>'digit', 'title'=>'销售价', 'name'=>'price', 'value'=>$info['price']);
        $form[] = array('type'=>'digit', 'title'=>'原价', 'name'=>'old_price', 'value'=>$info['old_price']);
        if($shop){
            $form[] = array('type'=>'digit', 'title'=>'会员价', 'name'=>'vip_price', 'value'=>$info['vip_price']);
            //商品参与分销以及佣金
            $form[] = array('type'=>'checkbox', 'title'=>'参与分销', 'name'=>'is_commission', 'value'=>$info['is_commission']?$info['is_commission']:0, 'checked'=>$info['is_commission']?true:false);
            $form[] = array('type'=>'number', 'title'=>'一级佣金比例(%)', 'name'=>'commission_one', 'value'=>$info['commission_one']);
            $form[] = array('type'=>'number', 'title'=>'二级佣金比例(%)', 'name'=>'commission_two', 'value'=>$info['commission_two']);
        }
        $form[] = array('type'=>'number', 'title'=>'库存', 'name'=>'stock', 'value'=>$info['stock']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'checkbox', 'title'=>'开启限购', 'name'=>'is_xian', 'value'=>$info['is_xian']?$info['is_xian']:0, 'checked'=>$info['is_xian']?true:false);
        $form[] = array('type'=>'number', 'title'=>'每人限购件数', 'name'=>'max_num', 'value'=>$info['max_num']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'商品图片', 'name'=>'pics', 'num'=>2, 'pics'=>$pics);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'textarea', 'title'=>'商品简介', 'name'=>'content', 'value'=>$info['content']);
        $res['form'] = $form;
        return $res;
    }
    private function getQiangForm(){
        $map['id'] = $_GET['id'];
        $info = M("Goods")->where($map)->find();
        // $pics = explode(',', $info['pics']);
        $res['add_url'] = "https://www.58zltc.com/api.php/Goods/add/id/{$_GET['id']}";

        $form[] = array('type'=>'checkbox', 'title'=>'开启限时抢购', 'name'=>'is_qiang', 'value'=>$info['is_qiang']?$info['is_qiang']:0, 'checked'=>$info['is_qiang']?true:false);
        $form[] = array('type'=>'date', 'title'=>'抢购开始日期', 'name'=>'start_date', 'value'=>$info['start_date']?$info['start_date']:date("Y-m-d"));
        $form[] = array('type'=>'time', 'title'=>'抢购开始时间', 'name'=>'start_time', 'value'=>$info['start_time']?$info['start_time']:date("H:i"));
        $form[] = array('type'=>'date', 'title'=>'抢购结束日期', 'name'=>'end_date', 'value'=>$info['end_date']?$info['end_date']:date("Y-m-d"));
        $form[] = array('type'=>'time', 'title'=>'抢购结束时间', 'name'=>'end_time', 'value'=>$info['end_time']?$info['end_time']:date("H:i"));
        $res['form'] = $form;
        return $res;
    }
    private function getPinForm(){
        $map['id'] = $_GET['id'];
        $info = M("Goods")->where($map)->find();
        // $pics = explode(',', $info['pics']);
        //$res['add_url'] = "https://www.58zltc.com/api.php/Goods/add/id/{$_GET['id']}";
        $res['add_url'] = "https://www.58zltc.com/api.php/Goods/add/id/{$_GET['id']}";
        $form[] = array('type'=>'checkbox', 'title'=>'开启拼团', 'name'=>'is_pin', 'value'=>$info['is_pin']?$info['is_pin']:0, 'checked'=>$info['is_pin']?true:false);
        $form[] = array('type'=>'number', 'title'=>'几人团', 'name'=>'tuan_need_num', 'value'=>$info['tuan_need_num']);
        $form[] = array('type'=>'digit', 'title'=>'拼团价', 'name'=>'tuan_price', 'value'=>$info['tuan_price']);
        $shop = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();
        if($shop){
            $form[] = array('type'=>'digit', 'title'=>'会员拼团价', 'name'=>'vip_pin_price', 'value'=>$info['vip_pin_price']);
        }
        $res['form'] = $form;
        return $res;
    }
    private function getKanForm(){
        $map['id'] = $_GET['id'];
        $info = M("Goods")->where($map)->find();
        // $pics = explode(',', $info['pics']);
        $res['add_url'] = "https://www.58zltc.com/api.php/Goods/add/id/{$_GET['id']}";

        $form[] = array('type'=>'checkbox', 'title'=>'开启砍价', 'name'=>'is_kan', 'value'=>$info['is_kan']?$info['is_kan']:0, 'checked'=>$info['is_kan']?true:false);
        $form[] = array('type'=>'checkbox', 'title'=>'只能底价购买', 'name'=>'kan_need_min', 'value'=>$info['kan_need_min']?$info['kan_need_min']:0, 'checked'=>$info['kan_need_min']?true:false);
        $form[] = array('type'=>'number', 'title'=>'砍到底价需要人数', 'name'=>'kan_need_num', 'value'=>$info['kan_need_num']);
        $form[] = array('type'=>'digit', 'title'=>'底价', 'name'=>'kan_price', 'value'=>$info['kan_price']);
        $shop = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();
        if($shop){
            $form[] = array('type'=>'digit', 'title'=>'会员底价', 'name'=>'vip_kan_price', 'value'=>$info['vip_kan_price']);
        }
        $res['form'] = $form;
        return $res;
    }

    public function add(){
        //print_r($_POST);exit;
        $postV = $_POST;
        unset($postV['is_xian']);
        unset($postV['max_num']);
        foreach ($postV as $key => $value) {
            if(!is_numeric($value) && empty($value)){

                $arr = array("err_code"=>400,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
            if($value === 'true'){
                $_POST[$key] = 1;
            }elseif($value === 'false'){
                $_POST[$key] = 0;
            }
        }
        if($_GET['id']){
            $map['wid'] = session('wid');
            $map['id'] = $_GET['id'];
            $map['openid'] = $_POST['openid'];
            $r = M("Goods")->where($map)->save($_POST);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $eq['wid'] = session('wid');
            $eq['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
            $_POST['wid'] = session('wid');
            $_POST['create_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("Goods")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }

    }

    public function del(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];
        $new['status'] = 0;

        if(M("Goods")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    public function verJionEndTime () {
        $id = I('id');
        $list = M('goods')->alias('a')->field('b.join_end_time')->join('tp_shop b on a.shop_id = b.shop_id')->where(['a.id' => $id])->find();
        $list['join_end_time'] > date('Y-m-d H:i:s', time())?$this->ajaxReturn(1):$this->ajaxReturn(0);
    }

    //所有抢购,拼团,减价商品
    public function allHouDong () {
        $map = array();
        //$map['a.wid'] = session('wid');
        $map['a.status'] = 1;
        if($_GET['shop_id']){
            $map['a.shop_id'] = $_GET['shop_id'];
        }
        $list = array();
        //减价
        $listKan = M("Goods")->alias('a')
                            ->field('a.*, b.join_end_time, b.cate')
                            ->join('tp_shop b on a.shop_id = b.shop_id')
                            ->where($map)
                            ->where(['a.is_kan' => 1])
                            ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                            ->order("last_time desc")
                            ->select();
        $list['jian'] = $listKan;
        //抢购
        $listQiang = M("Goods")->alias('a')
                                ->field('a.*, b.join_end_time, b.cate')
                                ->join('tp_shop b on a.shop_id = b.shop_id')
                                ->where($map)
                                ->where(['a.is_qiang' => 1])
                                ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                                ->order("last_time desc")
                                ->select();
        $list['qiang'] = $listQiang;
        //拼团
        $listPin = M("Goods")->alias('a')
                                ->field('a.*, b.join_end_time, b.cate')
                                ->join('tp_shop b on a.shop_id = b.shop_id')
                                ->where($map)
                                ->where(['a.is_pin' => 1])
                                ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                                ->order("last_time desc")
                                ->select();
        $list['pin'] = $listPin;
        //普通
        $listPu = M("Goods")->alias('a')
                            ->field('a.*, b.join_end_time, b.cate')
                            ->join('tp_shop b on a.shop_id = b.shop_id')
                            ->where($map)
                            ->where(['a.is_pin' => 0, 'a.is_kan' => 0, 'a.is_qiang' => 0])
                            ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
                            ->order("last_time desc")
                            ->select();
        $list['pu'] = $listPu;

        $this->ajaxReturn($list);
    }
}